package com.fyl.datasource.creator;

import com.fyl.datasource.config.DataSourceProperty;
import com.fyl.datasource.exception.ErrorCreateDataSourceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.Objects;

public abstract class AbstractDataSourceCreator implements DataSourceCreator, DataSourcePostProcessor {

    private static final Logger log = LoggerFactory.getLogger(AbstractDataSourceCreator.class);

    private static Method createMethod;
    private static Method typeMethod;
    private static Method urlMethod;
    private static Method usernameMethod;
    private static Method passwordMethod;
    private static Method driverClassNameMethod;
    private static Method buildMethod;

    static {
        //to support springboot 1.5 and 2.x
        Class<?> builderClass = null;
        try {
            builderClass = Class.forName("org.springframework.boot.jdbc.DataSourceBuilder");
        } catch (Exception ignored) {
        }
        if (builderClass == null) {
            try {
                builderClass = Class
                        .forName("org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder");
            } catch (Exception e) {
            }
        }
        if (builderClass != null) {
            try {
                createMethod = builderClass.getDeclaredMethod("create");
                typeMethod = builderClass.getDeclaredMethod("type", Class.class);
                urlMethod = builderClass.getDeclaredMethod("url", String.class);
                usernameMethod = builderClass.getDeclaredMethod("username", String.class);
                passwordMethod = builderClass.getDeclaredMethod("password", String.class);
                driverClassNameMethod = builderClass.getDeclaredMethod("driverClassName", String.class);
                buildMethod = builderClass.getDeclaredMethod("build");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public abstract DataSource createDynamicDataSource(DataSourceProperty dataSourceProperty);

    @Override
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        DataSource dataSource = createDynamicDataSource(dataSourceProperty);
        if (Objects.isNull(dataSource)) {
            dataSource = createBasicDataSource(dataSourceProperty);
        }
        postProcessAfterCreation(dataSourceProperty, dataSource);
        return dataSource;
    }


    /**
     * 创建基础数据源
     *
     * @param dataSourceProperty 数据源参数
     * @return 数据源
     */
    private DataSource createBasicDataSource(DataSourceProperty dataSourceProperty) {
        try {
            Object o1 = createMethod.invoke(null);
            Object o2 = typeMethod.invoke(o1, dataSourceProperty.getType());
            Object o3 = urlMethod.invoke(o2, dataSourceProperty.getUrl());
            Object o4 = usernameMethod.invoke(o3, dataSourceProperty.getUsername());
            Object o5 = passwordMethod.invoke(o4, dataSourceProperty.getPassword());
            Object o6 = driverClassNameMethod.invoke(o5, dataSourceProperty.getDriverClassName());
            return (DataSource) buildMethod.invoke(o6);
        } catch (Exception e) {
            throw new ErrorCreateDataSourceException(
                    "dynamic-datasource create basic database named " + dataSourceProperty.getPollName()
                            + " error");
        }
    }

    @Override
    public void postProcessAfterCreation(DataSourceProperty dataSourceProperty, DataSource dataSource) {
        String schema = dataSourceProperty.getSchema();
        if (StringUtils.hasText(schema)) {
            runScript(dataSource, schema, dataSourceProperty);
        }
        String data = dataSourceProperty.getData();
        if (StringUtils.hasText(data)) {
            runScript(dataSource, data, dataSourceProperty);
        }
    }

    private void runScript(DataSource dataSource, String location,
                           DataSourceProperty dataSourceProperty) {
        if (StringUtils.hasText(location)) {
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            populator.setContinueOnError(dataSourceProperty.isContinueOnError());
            populator.setSeparator(dataSourceProperty.getSeparator());
            ClassPathResource resource = new ClassPathResource(location);
            if (resource.exists()) {
                populator.addScript(resource);
                try {
                    DatabasePopulatorUtils.execute(populator, dataSource);
                    log.info("execute {} script success", location);
                } catch (Exception e) {
                    log.warn("execute sql error", e);
                }
            } else {
                log.error("could not find schema or data file {}", location);
            }
        }
    }
}
